-- EnemyStatusMonitor.lua
-- 敌人状态监视器：监控敌人状态并管理血条 - 修复drawPolygon参数问题

local EnemyStatusMonitor = {}
EnemyStatusMonitor.__index = EnemyStatusMonitor

function EnemyStatusMonitor.new(enemyId, enemyType)
    local instance = {
        enemyId = enemyId,
        enemyType = enemyType,
        
        -- 状态信息
        currentHealth = 100,
        maxHealth = 100,
        isAlive = true,
        isInvincible = false,
        invincibleTimer = 0,
        
        -- 血条
        healthBar = nil,
        healthBarNode = nil,
        
        -- 位置追踪
        lastPosition = {x = 0, y = 0},
        positionHistory = {},
        
        -- 状态变化
        stateHistory = {},
        
        -- 调试模式
        debugMode = true,
        
        -- 敌人类型的基础血量
        baseHealth = {
            sword = 100,
            archer = 80,
            broadsword = 120,
            boss = 500
        },
        
        -- 血条配置
        healthBarConfig = {
            width = 120,   -- 敌人血条较窄
            height = 16,   -- 敌人血条较矮
            offsetY = 60   -- 血条在敌人头顶上方的偏移量
        },
        
        -- 帧计数器
        frameCount = 0
    }
    
    -- 根据类型设置初始血量
    instance.maxHealth = instance.baseHealth[enemyType] or 100
    instance.currentHealth = instance.maxHealth
    
    return setmetatable(instance, EnemyStatusMonitor)
end

-- 创建红色血条
function EnemyStatusMonitor:createHealthBar()
    local Node = require("Node")
    local DrawNode = require("DrawNode")
    local Color = require("Color")
    
    if not DrawNode or not Color then
        print("无法创建血条：缺少DrawNode或Color模块")
        return nil
    end
    
    -- 血条尺寸
    local width = self.healthBarConfig.width
    local height = self.healthBarConfig.height
    
    -- 创建血条节点
    self.healthBarNode = Node()
    self.healthBarNode.zOrder = 999  -- 在角色之上
    
    -- 创建背景（暗红色）
    local bgDrawNode = DrawNode()
    local bgColor = Color(50, 0, 0, 220)  -- 暗红色背景
    
    -- 创建Vec2顶点数组
    local Vec2 = require("Vec2")
    local bgVerts = {
        Vec2(0, 0),
        Vec2(width, 0),
        Vec2(width, height),
        Vec2(0, height)
    }
    
    -- 使用drawPolygon的正确参数格式
    bgDrawNode:drawPolygon(bgVerts, bgColor)
    self.healthBarNode:addChild(bgDrawNode)
    
    -- 创建血量条（红色）
    local healthDrawNode = DrawNode()
    self.healthBarNode:addChild(healthDrawNode)
    
    -- 创建边框（亮红色）
    local borderDrawNode = DrawNode()
    local borderColor = Color(255, 100, 100, 200)  -- 亮红色边框
    
    -- 绘制4条边线
    borderDrawNode:drawSegment(Vec2(0, 0), Vec2(width, 0), 1, borderColor) -- 上边
    borderDrawNode:drawSegment(Vec2(width, 0), Vec2(width, height), 1, borderColor) -- 右边
    borderDrawNode:drawSegment(Vec2(width, height), Vec2(0, height), 1, borderColor) -- 下边
    borderDrawNode:drawSegment(Vec2(0, height), Vec2(0, 0), 1, borderColor) -- 左边
    
    self.healthBarNode:addChild(borderDrawNode)
    
    -- 存储血条组件
    self.healthBar = {
        node = self.healthBarNode,
        bgDrawNode = bgDrawNode,
        healthDrawNode = healthDrawNode,
        borderDrawNode = borderDrawNode,
        width = width,
        height = height,
        offsetY = self.healthBarConfig.offsetY
    }
    
    -- 初始隐藏血条（满血时不显示）
    self.healthBarNode.visible = false
    
    if self.debugMode then
        print(string.format("为 %s 创建红色血条", self.enemyId))
    end
    
    return self.healthBarNode
end

-- 更新血条
function EnemyStatusMonitor:updateHealthBar()
    if not self.healthBar or not self.healthBar.healthDrawNode then return end
    
    local percentage = self.maxHealth > 0 and (self.currentHealth / self.maxHealth) or 0
    
    -- 清除之前的血量显示
    self.healthBar.healthDrawNode:clear()
    
    -- 计算血量条宽度
    local healthWidth = self.healthBar.width * percentage
    
    if healthWidth > 0 then
        local Color = require("Color")
        local Vec2 = require("Vec2")
        
        -- 根据血量选择不同的红色
        local healthColor
        if percentage > 0.6 then
            healthColor = Color(255, 50, 50, 255)  -- 鲜红（高血量）
        elseif percentage > 0.3 then
            healthColor = Color(255, 100, 50, 255)  -- 橙红（中血量）
        else
            healthColor = Color(255, 150, 50, 255)  -- 橙黄（低血量）
        end
        
        -- 创建Vec2顶点数组
        local verts = {
            Vec2(0, 0),
            Vec2(healthWidth, 0),
            Vec2(healthWidth, self.healthBar.height),
            Vec2(0, self.healthBar.height)
        }
        
        self.healthBar.healthDrawNode:drawPolygon(verts, healthColor)
    end
    
    -- 控制血条显示：满血时不显示，受伤或低血量时显示
    if self.currentHealth <= 0 then
        self.healthBarNode.visible = false
    else
        self.healthBarNode.visible = (self.currentHealth < self.maxHealth or percentage < 0.99)
    end
end

-- 设置血条位置（跟随敌人）
function EnemyStatusMonitor:setHealthBarPosition(x, y)
    if not self.healthBarNode then return end
    
    -- 血条在敌人头顶上方
    local offsetY = self.healthBar.offsetY
    
    -- 直接设置位置
    self.healthBarNode.x = x
    self.healthBarNode.y = y + offsetY
end

-- 应用伤害
function EnemyStatusMonitor:applyDamage(damage)
    if not self.isAlive or self.isInvincible then
        return false
    end
    
    if damage <= 0 then
        return false
    end
    
    -- 计算实际伤害
    local actualDamage = math.floor(damage)
    local oldHealth = self.currentHealth
    self.currentHealth = math.max(0, self.currentHealth - actualDamage)
    
    -- 记录状态变化
    table.insert(self.stateHistory, {
        time = os.time(),
        event = "damage",
        damage = actualDamage,
        oldHealth = oldHealth,
        newHealth = self.currentHealth
    })
    
    -- 设置无敌帧（防止连续受伤）
    self.isInvincible = true
    self.invincibleTimer = 0.5  -- 0.5秒无敌时间
    
    -- 检查是否死亡
    if self.currentHealth <= 0 then
        self.isAlive = false
        table.insert(self.stateHistory, {
            time = os.time(),
            event = "death"
        })
        
        if self.debugMode then
            print(string.format("敌人 %s 死亡", self.enemyId))
        end
        
        -- 隐藏血条
        if self.healthBarNode then
            self.healthBarNode.visible = false
        end
    else
        if self.debugMode then
            print(string.format("敌人 %s 受到 %d 点伤害，剩余血量: %d/%d", 
                self.enemyId, actualDamage, self.currentHealth, self.maxHealth))
        end
    end
    
    -- 更新血条显示
    self:updateHealthBar()
    
    return true
end

-- 治疗
function EnemyStatusMonitor:heal(amount)
    if not self.isAlive then return false end
    
    if amount <= 0 then return false end
    
    local oldHealth = self.currentHealth
    self.currentHealth = math.min(self.maxHealth, self.currentHealth + amount)
    
    local healedAmount = self.currentHealth - oldHealth
    
    -- 记录状态变化
    table.insert(self.stateHistory, {
        time = os.time(),
        event = "heal",
        amount = healedAmount,
        oldHealth = oldHealth,
        newHealth = self.currentHealth
    })
    
    -- 更新血条显示
    self:updateHealthBar()
    
    if self.debugMode and healedAmount > 0 then
        print(string.format("敌人 %s 治疗 %d 点，当前血量: %d/%d", 
            self.enemyId, healedAmount, self.currentHealth, self.maxHealth))
    end
    
    return healedAmount > 0
end

-- 更新状态监视器
function EnemyStatusMonitor:update(dt, x, y)
    -- 更新无敌计时器
    if self.isInvincible then
        self.invincibleTimer = math.max(0, self.invincibleTimer - dt)
        if self.invincibleTimer <= 0 then
            self.isInvincible = false
        end
    end
    
    -- 更新血条位置
    if self.healthBarNode then
        self:setHealthBarPosition(x, y)
    end
    
    -- 记录位置历史（用于调试）
    if self.debugMode and self.frameCount % 60 == 0 then
        table.insert(self.positionHistory, {x = x, y = y, time = os.time()})
        
        -- 保持历史记录不超过100条
        if #self.positionHistory > 100 then
            table.remove(self.positionHistory, 1)
        end
    end
    
    -- 帧计数器
    self.frameCount = self.frameCount + 1
end

-- 获取状态信息
function EnemyStatusMonitor:getStatus()
    return {
        enemyId = self.enemyId,
        enemyType = self.enemyType,
        currentHealth = self.currentHealth,
        maxHealth = self.maxHealth,
        isAlive = self.isAlive,
        isInvincible = self.isInvincible,
        invincibleTimer = self.invincibleTimer,
        healthPercentage = self.maxHealth > 0 and (self.currentHealth / self.maxHealth) or 0,
        hasHealthBar = self.healthBarNode ~= nil,
        healthBarVisible = self.healthBarNode and self.healthBarNode.visible or false
    }
end

-- 获取状态历史
function EnemyStatusMonitor:getStateHistory()
    return self.stateHistory
end

-- 获取位置历史
function EnemyStatusMonitor:getPositionHistory()
    return self.positionHistory
end

-- 重置状态监视器
function EnemyStatusMonitor:reset()
    self.currentHealth = self.maxHealth
    self.isAlive = true
    self.isInvincible = false
    self.invincibleTimer = 0
    self.stateHistory = {}
    self.positionHistory = {}
    
    if self.healthBarNode then
        self.healthBarNode.visible = false
    end
    
    if self.debugMode then
        print(string.format("敌人状态监视器已重置: %s", self.enemyId))
    end
end

-- 清理资源
function EnemyStatusMonitor:cleanup()
    if self.healthBarNode then
        if self.healthBarNode.parent then
            self.healthBarNode:removeFromParent()
        end
        self.healthBarNode = nil
    end
    
    self.healthBar = nil
    
    if self.debugMode then
        print(string.format("清理敌人状态监视器: %s", self.enemyId))
    end
end

return EnemyStatusMonitor